/**
 * AmqpConfiguration.java
 */
package com.tobeface.sns.infrastructure.amqp.config;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author Dylan
 * @time 2012-8-2
 */
public abstract class AmqpConfiguration {

	protected final static String CHAT_EXCHANGE_NAME = "amqp.sinzv.chat.exchange";
	protected final static String CHAT_QUEUE_NAME = "amqp.sinzv.chat.queue";
	
	private ExecutorService executor = Executors.newFixedThreadPool(10);
	private Connection conn;
	private Channel channel;
	private String virtualHost = "tobeface";
	private String userName = "tobeface";
	private String password = "tobeface";
	private String host = "192.168.3.239";
	private int port = 5672;

	public AmqpConfiguration(){
		
	}
	public Connection getConnection() throws IOException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUsername(userName);
		factory.setPassword(password);
		factory.setVirtualHost(virtualHost);
		factory.setHost(host);
		factory.setPort(port);
		conn = factory.newConnection(executor);
		return conn;
	}

	protected abstract Channel initChannel(Channel channel);

	public Channel getChannel() throws IOException {
		channel = getConnection().createChannel();
		channel = initChannel(channel);
		return channel;
	}
	
	public void destroy(){
		try {
			if(null != channel){
				if(this.channel.isOpen()){
					this.channel.close();
				}
				this.channel = null;
				
			}
			if(null != conn){
				if(this.conn.isOpen()){
					this.conn.close();
				}
				this.conn = null;
			}
		} catch (IOException e) {
			throw new RuntimeException("cant't close the connection or channel", e);
		}
		
	}

}
